package com.lanou.bookstore.category.service;

import com.lanou.bookstore.book.dao.BookDao;
import com.lanou.bookstore.book.dao.BookDaoImpl;
import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.category.dao.CategoryDao;
import com.lanou.bookstore.category.dao.CategoryDaoImpl;
import com.lanou.bookstore.category.domain.Category;

import java.util.List;

public class CategoryServiceImpl implements CategoryService {

    CategoryDao cate = new CategoryDaoImpl();
    BookDao book = new BookDaoImpl();

    @Override
    public List<Category> queryAll() {

        List<Category> list = cate.queryAll();

        return list;
    }

    @Override
    public void add(String cate1) throws Exception {
        List<Category> list = cate.queryAll();

        int max = -1;


        for (Category category : list) {

            if (category.getCname().equals(cate1)){

                throw new Exception("此分类已经存在!!");
            }
        }
        for (Category category : list) {
            if (Integer.parseInt(category.getCid()) > max){
                max = Integer.parseInt(category.getCid());
            }
        }
        max++;

        Category cate2 = new Category();
        cate2.setCid(Integer.toString(max));
        cate2.setCname(cate1);
        cate.addCategory(cate2);



    }

    @Override
    public void delete(String cate3) throws Exception{

        List<Book> list = book.queryByCate(cate3);

        if (list.size() == 0){
            cate.delete(cate3);
        }else {
            throw new Exception("此分类下还有图书,不能删除分类!!");
        }


    }

    @Override
    public void mod(String cate2, String input){
        cate.modCat(cate2,input);
    }
}
